<?php

namespace App\Model\PssModel;

use App\Model\BaseModel\BasePssModel;
use App\Service\Code\Normal;
use App\Service\BaseService;
use App\Service\CommonDataService\RegionDataService;

class TemplateArea extends BasePssModel
{
    public $table = 'template_area';
    const REDIS_KEY = 'REDIS_TEMPLATE_AREA_KEY';
    /**
     * 获取区域对应的运费信息
     * @param array $regions
     */
    public function getThirdPartyCountryListByRegions( $regions = [] ) 
    {
        $redis          = BaseService::instance()->getRedisObj();
        $regionList     = $this->getRegionListByCache($redis);
        
        //省
        $provinceInfo   = $redis->hget(self::REDIS_KEY,$regions['province']);
        if( empty($provinceInfo) ) {
            return Normal::returnCode(Normal::FAIL,"获取服务收货地址省份解析异常，请联系管理员");
        }
        $provinceInfo = json_decode($provinceInfo,true);
        
        //市
        $cityList     = array_column($provinceInfo['list'],null,'name');
        if( empty($cityList[$regions['city']]) ) {
            return Normal::returnCode(Normal::FAIL,"获取服务收货地址市解析异常，请联系管理员");
        }
        $cityInfo     = $cityList[$regions['city']];
        
        //区
        $districtInfo = array_column($cityInfo['list'],null,'name');
        if( empty($districtInfo[$regions['district']]) ) {
            return Normal::returnCode(Normal::FAIL,"获取服务收货地址区/县解析异常，请联系管理员");
        }
        $districtInfo = $districtInfo[$regions['district']];
        
        $province_id    = $provinceInfo['id'];
        $city_id        = $cityInfo['id'];
        $district_id    = $districtInfo['id'];
        $idsMap         = [$province_id,$city_id,$district_id];
        $tdal           = TemplateDeliveryAreaList::instance()->select(['tda_id','area_id'])->whereIn('area_id',$idsMap)->get()->toArray();
        if( empty($tdal) ) {
            $tda_id = 1;//默认使用全国统一模板
        } else {
            //使用指定区域模板
            $tdaMap = array_column($tdal,'tda_id','area_id');
            if( isset($tdaMap[$district_id]) ) {
                $tda_id = $tdaMap[$district_id];
            } else if( isset($tdaMap[$city_id]) ) {
                $tda_id = $tdaMap[$city_id];
            } else if( isset($tdaMap[$province_id]) ) {
                $tda_id = $tdaMap[$province_id];
            } else {
                $tda_id = 1;//默认使用全国统一模板
            }
        }
        $deliveryInfo = TemplateDeliveryArea::instance()->info(['id'=>$tda_id],['init_weight','init_money','increase_weight','increase_money']);
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'tda_id'            => $tda_id??0,
            'init_weight'       => $deliveryInfo['init_weight']??0,
            'init_money'        => $deliveryInfo['init_money']??0.00,
            'increase_weight'   => $deliveryInfo['increase_weight']??0,
            'increase_money'    => $deliveryInfo['increase_money']??0.00,
        ]);
    }
    
    /**
     * 获取用户下单的区域地址
     * @param array $templateList
     * @param array $addressInfo
     * @return mixed
     */
    public function getUserRegionIdsByAddress( array $templateList = [] , array $regions = [], array $noSaleArea = [] )
    {
        
        //调用公共数据接口来获取区域id
        $regionData=RegionDataService::instance()->queryRegionByAddress($regions);
        if ($regionData['code']!=Normal::SUC){
            return $regionData;
        }
        if (empty($regionData['data'])){
            return Normal::returnCode(Normal::FAIL,'下单收货地址获取失败');
        }
        $regionInfo     = $regionData['data'];

        $province_id    = $regionInfo['province_id'];
        $city_id        = $regionInfo['city_id'];
        $district_id    = $regionInfo['district_id'];

        //判断是否在禁售区域内
        if (in_array($province_id,$noSaleArea) || in_array($city_id,$noSaleArea) || in_array($district_id,$noSaleArea)) {
            return Normal::returnCode(Normal::FAIL,'下单收获地址在禁售区域中,无法发货');
        }

        $terminal_template_list = [];
        foreach ($templateList as $template_id => $item )
        {
            $tdaMap = array_column($item,null,'tda_area_id');
            if( isset($tdaMap[$district_id]) ) {
                $terminal_template_list[$template_id] = $tdaMap[$district_id];
            } else if( isset($tdaMap[$city_id]) ) {
                $terminal_template_list[$template_id] = $tdaMap[$city_id];
            } else if( isset($tdaMap[$province_id]) ) {
                $terminal_template_list[$template_id] = $tdaMap[$province_id];
            }
            unset($item);
        }
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'template_list' => $terminal_template_list
        ]);
    }
    
    /**
     * 设置模板运费REDIS CACHE
     */
    public function getRegionListByCache($redis) 
    {
        if( $redis->hlen(self::REDIS_KEY) > 0 ) {
            return Normal::returnCode(Normal::SUC,"获取成功");
        }
        
        $list = TemplateArea::instance()->rows();
        if( empty($list) ) {
            return Normal::returnCode(Normal::FAIL,"模板运费地址不能为空");
        }
        $listTree = tree($list, 0, 'id', 'pid');
        foreach ($listTree as $tree ) {
            $redis->hset(self::REDIS_KEY,$tree['name'],json_encode($tree,JSON_UNESCAPED_UNICODE));
        }
        return Normal::returnCode(Normal::SUC,"设置成功");
    }
}